﻿var TMMService = function (token, svrUrl) {
    var baseAddress = $("[id*='BaseUrlHF']").val();

    var JSON_API_URL = baseAddress;

    var moduleCode = "";

    var MobilePushMessagingServiceUrl = $("[id*='MobilePushMessagingServiceUrlHF']").val();

    var apiToken = token || "";
    var serverUrl = svrUrl || "";
    var Endpoints =
    {
        Redirect: 'Home/',
        Security: 'SecurityService.svc/',
        TMM: 'TMMService.svc/',
        General: 'GeneralService.svc/',
        Cereri: 'CereriService.svc/',
        Pontaj: 'PontajService.svc/',
        Notifications: 'NotificationsService.svc/'
    };

    var callAjax = function (serviceUrl, myData, callback, type, dataType) {
        if (apiToken && apiToken.length && myData)
            myData.token = apiToken;

        type = type || "GET";

        if (type == 'POST')
            myData = JSON.stringify(myData);

        $.ajax({
            url: serviceUrl,
            data: myData,
            timeout: 2400000,
            dataType: dataType || "json",
            cache: false,
            async: true,
            type: type,
            contentType: "application/json; charset=utf-8",
            processData: type == 'GET',
            success: function (response) {
                if (callback)
                    callback(response ? (response.d ? response.d : response) : {});
            },
            error: function (jqXHR, textStatus, errorThrown) {
                var errorText = translate('General_EroareServer') + " TS: " + textStatus + " E: " + (errorThrown ? errorThrown.responseText : '');
                app.hideLoadingScreen();
                if (callback)
                    callback({ Exception: { Message: errorText } });
            },
            beforeSend: function (jqXHR) {
                if (apiToken && apiToken.length)
                    jqXHR.setRequestHeader('token', apiToken);
                jqXHR.setRequestHeader('module_code', moduleCode || "");

                jqXHR.setRequestHeader("Cache-Control", "no-cache");
                jqXHR.setRequestHeader("pragma", "no-cache");
            }
        });
    };

    return {
        TMM: {
            ReadNotification: function (msgId, callback) {
                var data = {
                    msg_id: msgId
                };

                callAjax(serverUrl + Endpoints.TMM + 'ReadNotification', data, callback);
            },
            ReadAllNotifications: function (callback) {
                var data = {};
                callAjax(serverUrl + Endpoints.TMM + 'ReadAllNotifications', data, callback);
            },
            GetCerereConcediu: function (ccdId, callback) {
                var data = {
                    ccd_id: ccdId
                };
                callAjax(serverUrl + Endpoints.TMM + 'GetCerereConcediu', data, function (response) {
                    var fr = response.FinalResult;
                    if (fr) {
                        fr.DataStart = fr.DataStart.parseDate();
                        fr.DataSfarsit = fr.DataSfarsit.parseDate();
                        if (fr.MinDate)
                            fr.MinDate = fr.MinDate.parseDate();
                    }
                    if (callback)
                        callback(response);
                });
            },
            GetCereriConcediu: function (startIndex, setSize, nume, marca, elm_id, tco_id, status, pct_id, dpt_id, dateStart, dateEnd, stp_id, ignoreSelf, pra_id_filter, callback) {
                var data = {
                    startIndex: startIndex,
                    setSize: setSize,
                    nume: nume || "",
                    marca: marca || "",
                    elm_id: elm_id || 0,
                    tco_id: tco_id || 0,
                    pct_id: pct_id || 0,
                    dpt_id: dpt_id || 0,
                    status: status != null ? status : -1,
                    dateStart: dateStart || "",
                    dateEnd: dateEnd || "",
                    stp_id: stp_id || 0,
                    ignoreSelf: ignoreSelf || false,
                    pra_id_filter: pra_id_filter || 0
                };
                callAjax(serverUrl + Endpoints.TMM + 'GetCereriConcediu', data, function (response) {
                    if (callback)
                        callback(response);
                });
            },
            GetDashboardData_CereriConcedii: function (callback) {
                callAjax(serverUrl + Endpoints.TMM + 'GetDashboardData_CereriConcedii', {}, function (response) {
                    if (callback)
                        callback(response);
                });
            },
            GetDataAngajare: function (pra_id, callback) {
                var data = {
                    pra_id: pra_id
                };
                callAjax(serverUrl + Endpoints.TMM + 'GetDataAngajare', data, function (response) {
                    if (callback)
                        callback(response);
                });
            },
            GetSituatieCO: function (an, pra_id, callback) {
                var data = {
                    an: an,
                    pra_id: pra_id
                };
                callAjax(serverUrl + Endpoints.TMM + 'GetSituatieCO', data, function (response) {
                    if (callback)
                        callback(response);
                });
            },
            GetTMMData: function (callback) {
                callAjax(serverUrl + Endpoints.TMM + 'GetTMMData', {}, function (response) {
                    if (response.FinalResult)
                        response.FinalResult.Setari.RestrictionDate = response.FinalResult.Setari.RestrictionDate.parseDate();
                    if (callback)
                        callback(response);
                });
            },
            GetUserInfo: function (callback) {
                callAjax(serverUrl + Endpoints.TMM + "GetTMMUserInfo", {}, callback);
            },
            SaveUserPicture: function (picture, callback) {
                var data = {
                    picture: picture
                };
                callAjax(serverUrl + Endpoints.TMM + "SaveUserPicture", data, callback, "POST", null, true);
            },
            GetDictionary: function (callback) {
                callAjax(serverUrl + Endpoints.TMM + "GetDictionary", {}, callback);
            },
            GetSoldCO: function (an, pra_id, callback) {
                var data = {
                    an: an,
                    pra_id: pra_id
                };
                callAjax(serverUrl + Endpoints.TMM + "GetSoldCO", data, function (response) {
                    if (callback)
                        callback(response);
                });
            },
            GetNotifications: function (startIndex, setSize, lastDate, callback) {
                var data = {
                    startIndex: startIndex,
                    setSize: setSize,
                    lastDate: lastDate
                };
                callAjax(serverUrl + Endpoints.TMM + "GetNotifications", data, function (response) {
                    if (callback)
                        callback(response);
                });
            },
            GetCentreCost: function (nume, startIndex, setSize, callback) {
                var data = {
                    nume: nume,
                    startIndex: startIndex,
                    setSize: setSize
                };
                callAjax(serverUrl + Endpoints.TMM + "GetCentreCost", data, function (response) {
                    if (callback)
                        callback(response);
                });
            },
            GetUnreadNotificationsCount: function (callback) {
                var data = {

                };
                callAjax(serverUrl + Endpoints.TMM + "GetUnreadNotificationsCount", data, function (response) {
                    if (callback)
                        callback(response);
                });
            },
            DeleteNotification: function (msg_id, callback) {
                var data = {
                    msg_id: msg_id
                };
                callAjax(serverUrl + Endpoints.TMM + "DeleteNotification", data, function (response) {
                    if (callback)
                        callback(response);
                }, 'POST');
            }
        },
        Redirect: {
            GetConnectionUrl: function (serverCode, callback) {
                var data = {
                    serverCode: serverCode
                };
                callAjax(JSON_API_URL + Endpoints.Redirect + 'GetConnectionUrl', data, function (response) {
                    if (response)
                        serverUrl = response.ServiceAddress;

                    if (callback)
                        callback(response);
                }, "GET", "json");
            },
            GetMinVersion: function (platform, callback) {
                var data = {
                    platform: platform
                };

                callAjax(JSON_API_URL + Endpoints.Redirect + 'GetMinVersion', data, function (response) {
                    serverUrl = response;
                    if (callback)
                        callback(response);
                }, "GET", "json");
            },
            GetAvailableCompanies: function (server, username, password, liso, callback) {
                var data = {
                    server: server,
                    username: username,
                    password: password,
                    liso: liso
                };
                callAjax(JSON_API_URL + Endpoints.Redirect + 'GetAvailableCompanies', data, function (response) {
                    if (callback)
                        callback(response);
                }, "POST", "json");
            },
            GetConnectionData: function (server, username, password, companyId, liso, callback) {
                var data = {
                    server: server,
                    username: username,
                    password: password,
                    companyId: companyId,
                    liso: liso
                };
                callAjax(JSON_API_URL + Endpoints.Redirect + 'GetConnectionData', data, function (response) {
                    if (callback)
                        callback(response);
                }, "POST", "json");
            }
        },
        Security: {
            GetAvailableCompanies: function (username, password, callback) {
                var data = {
                    username: username,
                    password: password
                };

                callAjax(serverUrl + Endpoints.Security + 'GetAvailableCompanies', data, function (response) {
                    if (callback)
                        callback(response);
                });
            },
            Connect: function (username, password, company, selectedRole, language, appVersion, useSAAS, company_id, prsId, popId, userId, profileId, appId, personGuid, callback) {
                var data = {
                    username: username,
                    password: password,
                    company: company,
                    selectedRole: selectedRole,
                    appCode: "TMM",
                    language: language,
                    appVersion: appVersion || "0",
                    ip: "",
                    userAgent: "",
                    useSAAS: useSAAS,
                    company_id: company_id,
                    prsId: prsId || 0,
                    popId: popId || 0,
                    userId: userId,
                    profileId: profileId,
                    app_id: appId,
                    prsGuid: personGuid
                };

                callAjax(serverUrl + Endpoints.Security + 'Connect', data, function (response) {
                    try {
                        if (response)
                            response = JSON.parse(response);

                        if (response && response.FinalResult)
                            apiToken = response.FinalResult.Token;

                        if (callback)
                            callback(response);
                    }
                    catch (err) {
                        if (callback)
                            callback({ Exception: { Message: err.message } });
                    }
                });
            },
            getServerUrl: function () {
                return serverUrl;
            },
            resetServerUrl: function () {
                serverUrl = "";
            },
            getToken: function () {
                return apiToken;
            },
            resetToken: function () {
                apiToken = "";
            },
            ChangePassword: function (oldPassword, newPassword, callback) {
                var data = {
                    oldPassword: oldPassword,
                    newPassword: newPassword
                };

                callAjax(serverUrl + Endpoints.Security + "SavePassword", data, callback, "POST");
            },
            ChangeLanguage: function (language, callback) {
                var data = {
                    language: language
                };

                callAjax(serverUrl + Endpoints.Security + "ChangeLanguage", data, callback);
            }
        },
        General: {
            GetSubordinatesList: function (startIndex, size, textFilter, pct_id, dpt_id, fnc_id, cautaInNumeMarcaCNP, callback) {
                var data = {
                    startIndex: startIndex,
                    size: size,
                    textFilter: textFilter || "",
                    pct_id: pct_id || 0,
                    dpt_id: dpt_id || 0,
                    fnc_id: fnc_id || 0,
                    cautaInNumeMarcaCNP: cautaInNumeMarcaCNP || false
                };
                callAjax(serverUrl + Endpoints.General + 'GetSubordinatesList', data, function (response) {
                    if (callback)
                        callback(response);
                });
            },
            GetSalariati: function (an, luna, startIndex, noOfRecords, nume, marca, pct_id, dpt_id, fnc_id, grp_id, act_id, cc_id, pontajLevelType, loadExtended, rol_type, callback) {
                var data = {
                    an: an,
                    luna: luna,
                    startIndex: startIndex || 0,
                    noOfRecords: noOfRecords || 0,
                    nume: nume || "",
                    marca: marca || "",
                    pct_id: pct_id || 0,
                    dpt_id: dpt_id || 0,
                    fnc_id: fnc_id || 0,
                    grp_id: grp_id || 0,
                    act_id: act_id || 0,
                    cc_id: cc_id || 0,
                    pontajLevelType: pontajLevelType || 0,
                    loadExtended: loadExtended || false,
                    rol_type: rol_type || ""
                };

                callAjax(serverUrl + Endpoints.General + 'GetSalariati', data, callback);
            },
            GetSalariatiSimple: function (an, luna, startIndex, noOfRecords, nume, marca, pct_id, dpt_id, fnc_id, grp_id, act_id, cc_id, pontajLevelType, loadExtended, rol_type, callback) {
                var data = {
                    an: an,
                    luna: luna,
                    startIndex: startIndex || 0,
                    noOfRecords: noOfRecords || 0,
                    nume: nume || "",
                    marca: marca || "",
                    pct_id: pct_id || 0,
                    dpt_id: dpt_id || 0,
                    fnc_id: fnc_id || 0,
                    grp_id: grp_id || 0,
                    act_id: act_id || 0,
                    cc_id: cc_id || 0,
                    pontajLevelType: pontajLevelType || 0,
                    loadExtended: loadExtended || false,
                    rol_type: rol_type || ""
                };

                callAjax(serverUrl + Endpoints.General + 'GetSalariatiSimple', data, callback);
            },
            GetSubordinateInfo: function (pra_id, callback) {
                var data = {
                    pra_id: pra_id
                };
                callAjax(serverUrl + Endpoints.General + "GetSubordinateInfo", data, function (response) {
                    if (callback)
                        callback(response);
                });
            },
            GetDimensionsEntries: function (input, data_start, data_end, callback) {
                var data = {
                    input: input,
                    data_start: data_start,
                    data_end: data_end
                };
                callAjax(serverUrl + Endpoints.General + "GetDimensionsEntries", data, function (response) {
                    if (callback)
                        callback(response);
                });
            },
            GetPuncteLucru: function (textFilter, startIndex, setSize, callback) {
                var data = {
                    textFilter: textFilter,
                    startIndex: startIndex,
                    setSize: setSize
                };
                callAjax(serverUrl + Endpoints.General + "GetPuncteLucru", data, function (response) {
                    if (callback)
                        callback(response);
                });
            },
            GetDepartamente: function (pct_id, textFilter, startIndex, setSize, callback) {
                var data = {
                    pct_id: pct_id,
                    textFilter: textFilter,
                    startIndex: startIndex,
                    setSize: setSize
                };
                callAjax(serverUrl + Endpoints.General + "GetDepartamente", data, function (response) {
                    if (callback)
                        callback(response);
                });
            },
            GetFunctii: function (textFilter, startIndex, setSize, callback) {
                var data = {
                    textFilter: textFilter,
                    startIndex: startIndex,
                    setSize: setSize
                };
                callAjax(serverUrl + Endpoints.General + "GetFunctii", data, function (response) {
                    if (callback)
                        callback(response);
                });
            }
        },
        Cereri: {
            GetTipuriConcedii: function (callback) {
                callAjax(serverUrl + Endpoints.Cereri + 'GetTipuriConcedii', {}, function (response) {
                    if (callback)
                        callback(response);
                });
            },
            GetSubtipuriConcedii: function (elm_id, tco_id, callback) {
                var data = {
                    elm_id: elm_id || 0,
                    tco_id: tco_id || 0
                };

                callAjax(serverUrl + Endpoints.Cereri + 'GetSubtipuriConcedii', data, function (response) {
                    if (callback)
                        callback(response);
                });
            },
            GetAudit: function (ccd_id, needsPhotos, callback) {
                var data = {
                    ccd_id: ccd_id,
                    needsPhotos: needsPhotos
                };

                callAjax(serverUrl + Endpoints.Cereri + 'GetAudit', data, function (response) {

                    if (response.FinalResult)
                        for (var i = 0; i < response.FinalResult.length; i++) {
                            var a = response.FinalResult[i];
                            if (a.DataModificare)
                                a.DataModificare = a.DataModificare.parseDate();
                        }

                    if (callback)
                        callback(response);
                });
            },
            SalvareCerere: function (ccd_id, pra_id_from, dataStart, dataEnd, elm_id, tco_id, stp_id, descriere, cc_id, dimensiuni, language, documente, motivModificare, pra_id_inlocuitor, callback) {
                var cerere = {
                    CCD_ID: ccd_id || null,
                    PRA_ID_FROM: pra_id_from,
                    StartDate: dataStart,
                    EndDate: dataEnd,
                    ELM_ID: elm_id,
                    TCO_ID: tco_id,
                    STP_ID: stp_id,
                    Descriere: descriere || "",
                    CC_ID: cc_id,
                    Dimensions: dimensiuni || "",
                    Documents: documente,
                    MotivModificare: motivModificare || "",
                    PRA_ID_INLOCUITOR: pra_id_inlocuitor || 0
                };

                var data = {
                    cerere: cerere,
                    language: language
                };

                callAjax(serverUrl + Endpoints.Cereri + 'Salvare', data, function (response) {
                    if (callback)
                        callback(response);
                }, 'POST');
            },
            StergeCerere: function (ccd_id, callback) {
                var data = {
                    ccd_id: ccd_id
                };

                callAjax(serverUrl + Endpoints.Cereri + 'StergeCerere', data, function (response) {
                    if (callback)
                        callback(response);
                }, 'POST');
            },
            AprobaCerere: function (ccd_id, callback) {
                var data = {
                    ccd_id: ccd_id
                };

                callAjax(serverUrl + Endpoints.Cereri + 'AprobaCerere', data, function (response) {
                    if (callback)
                        callback(response);
                }, 'POST');
            },
            RefuzaCerere: function (ccd_id, motiv, callback) {
                var data = {
                    ccd_id: ccd_id,
                    motiv: motiv
                };

                callAjax(serverUrl + Endpoints.Cereri + 'RefuzaCerere', data, function (response) {
                    if (callback)
                        callback(response);
                }, 'POST');
            },
            GetZileLucratoare: function (dataStart, dataSfarsit, pra_id, shift_set, callback) {
                var data = {
                    dataStart: dataStart,
                    dataSfarsit: dataSfarsit,
                    pra_id: pra_id,
                    shift_set: shift_set || false
                };
                callAjax(serverUrl + Endpoints.Cereri + "GetZileLucratoare", data, function (response) {
                    if (callback)
                        callback(response);
                });
            }
        },
        PushMessaging: {
            RegisterDevice: function (deviceId, mobilePlatform, aid, company, usr_login, prs_id, language, callback) {
                var data = {
                    device_id: escape(deviceId.toString()),
                    mobilePlatform: mobilePlatform,
                    aid: aid,
                    company: company,
                    usr_login: usr_login || "",
                    prs_id: prs_id || 0,
                    language: language
                };

                callAjax(MobilePushMessagingServiceUrl + "RegisterDevice", data, callback, 'POST');
            },
            UnregisterDevice: function (device_id, mobilePlatform, aid, callback) {
                var data = {
                    device_id: device_id || "",
                    mobilePlatform: mobilePlatform,
                    aid: aid
                };

                callAjax(MobilePushMessagingServiceUrl + "UnregisterDevice", data, callback, 'POST');
            },
            InvalidateDeviceInfo: function (deviceId, aid, callback) {
                var data = {
                    device_id: escape(deviceId.toString()),
                    aid: aid
                };

                callAjax(MobilePushMessagingServiceUrl + "InvalidateDeviceInfo", data, callback, 'POST');
            }
        },
        Pontaj: {
            GetDimensiuniStructuri: function (callback) {
                callAjax(serverUrl + Endpoints.Pontaj + 'GetDimensiuniStructuri', {}, function (response) {
                    if (callback)
                        callback(response);
                });
            },
            GetDimensiuni: function (cstr_id, name, status, startIndex, pageSize, callback) {
                var data = {
                    cstr_id: cstr_id,
                    name: name,
                    status: status,
                    startIndex: startIndex,
                    pageSize: pageSize
                };
                callAjax(serverUrl + Endpoints.Pontaj + 'GetDimensiuni', data, function (response) {
                    if (callback)
                        callback(response);
                });
            },
            GetDimensiuniAll: function (dimensions, callback) {
                var data = {
                    dimensions: dimensions
                };
                callAjax(serverUrl + Endpoints.Pontaj + 'GetDimensiuniAll', data, function (response) {
                    if (callback)
                        callback(response);
                });
            }
        },
        Notifications: {
            SetNotificationsFromCerereAsRead: function (ccdId, callback) {
                var data = {
                    ccd_id: ccdId
                };
                callAjax(serverUrl + Endpoints.Notifications + 'SetNotificationsFromCerereAsRead', data, function (response) {
                    if (callback)
                        callback(response);
                });
            }
        },
        setModuleCode: function (code) {
            moduleCode = code;
        }
    };
};